package com.itheima.ydd.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.ydd.common.R;
import com.itheima.ydd.common.ResultData;
import com.itheima.ydd.dto.SysMenuDto;
import com.itheima.ydd.dto.SysRoleDto;
import com.itheima.ydd.entity.SysMenu;
import com.itheima.ydd.entity.SysRole;
import com.itheima.ydd.entity.SysRoleMenu;
import com.itheima.ydd.entity.SysUser;
import com.itheima.ydd.service.ISysMenuService;
import com.itheima.ydd.service.ISysRoleMenuService;
import com.itheima.ydd.service.ISysRoleService;
import com.itheima.ydd.service.ISysUserService;
import com.sun.scenario.effect.impl.prism.ps.PPSRenderer;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.omg.CORBA.PUBLIC_MEMBER;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import sun.dc.pr.PRError;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色表 前端控制器
 * </p>
 *
 * @author author
 * @since 2022-05-22
 */
@Slf4j
@RestController
@RequestMapping("/sys_role")
public class SysRoleController {
    @Autowired
    private ISysRoleService iSysRoleService;
    @Autowired
    private ISysRoleMenuService iSysRoleMenuService;
    @Autowired
    private ISysMenuService iSysMenuService;
    @Autowired
    private ISysUserService iSysUserService;

    /**
     * 修改角色数据
     *
     * @return
     */
    @PostMapping("update")
    public ResultData update(@RequestBody SysRoleDto sysRoleDto) {
        iSysRoleService.updateById(sysRoleDto);
        log.info("前端穿来的数据:{}", sysRoleDto);
        log.info("前端穿来的数据:{}", sysRoleDto.getId());

        // 修改菜单信息
        // 删除原始菜单数据
        LambdaQueryWrapper<SysRoleMenu> lqw = new LambdaQueryWrapper<>();
        lqw.in(SysRoleMenu::getRoleId, sysRoleDto.getId());
        iSysRoleMenuService.remove(lqw);
        // 添加新增信息
        List<String> role_menus = sysRoleDto.getRole_menus();
        List<SysRoleMenu> list = new ArrayList<>();
        for (String role_menu : role_menus) {
            SysRoleMenu sysRoleMenu = new SysRoleMenu();
            sysRoleMenu.setRoleId(sysRoleDto.getId());
            sysRoleMenu.setMenuId(role_menu);
            list.add(sysRoleMenu);
        }
        iSysRoleMenuService.saveBatch(list);
        ResultData resultData = new ResultData();
        resultData.setData("修改成功");
        resultData.setErrmsg("修改成功");
        resultData.setErrno(0);
        return resultData;

    }


    /**
     * 数据回显
     *
     * @param id
     * @return
     */
    @GetMapping("rowInfo")
    public ResultData rowInfo(String id) {
        SysRole byId = iSysRoleService.getById(id);
        SysRoleDto sysRoleDto = new SysRoleDto();
        // 数据拷贝
        BeanUtils.copyProperties(byId, sysRoleDto);
        // 获取角色权限id集合
        LambdaQueryWrapper<SysRoleMenu> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SysRoleMenu::getRoleId, id);
            List<SysRoleMenu> list = iSysRoleMenuService.list(lqw);
       // 存放菜单id的集合
        List<String> menuList = new ArrayList<>();

        if (list!=null){
                // 根据id集合得到菜单集合
                for (SysRoleMenu sysRoleMenu : list) {
                    // 菜单id
                    String menuId = sysRoleMenu.getMenuId();
                    menuList.add(menuId);
                }
            }
        // 所有被勾选的集合菜单
        List<SysMenu> menuList1 = iSysMenuService.listByIds(menuList);
        //LambdaQueryWrapper<SysMenu> lqw1 = new LambdaQueryWrapper();
        // 获取 pid = 0 的一级菜单
        /*lqw1.eq(SysMenu::getPid, 0);
        List<SysMenu> listOne = iSysMenuService.list(lqw1);*/
        for (SysMenu sysMenu : menuList1) {
            if(sysMenu.getPid() == 0){
                diGui(sysMenu);
            }
        }

        sysRoleDto.setAuthList(menuList1);
        ResultData resultData = new ResultData();
        resultData.setData(sysRoleDto);
        resultData.setErrmsg("");
        resultData.setErrno(0);
        return resultData;
    }

    // 递归方法
    private SysMenu diGui(SysMenu sysMenu){
        // 传来一级菜单
        LambdaQueryWrapper<SysMenu> lqw = new LambdaQueryWrapper<>();
        // pid = id 为 二级菜单
        lqw.eq(SysMenu::getPid,sysMenu.getId());
        // 二级菜单集合
        List<SysMenu> listTwo = iSysMenuService.list(lqw);

        // 判断是否有没有二级菜单
        if (listTwo == null || listTwo.size() == 0){
            // 没有
            return null;
        }
        // 有
        // 存入list中
        sysMenu.setChildren(listTwo);
        // 继续递归
        for (SysMenu menu : listTwo) {
            diGui(menu);
        }
        // 没有 返回
        return sysMenu;

    }


    /**
     * 删除角色数据
     *
     * @param id
     * @return
     */
    @GetMapping("del")
    public ResultData del(String id) {
        // 根据id 查user表看有无关联
        LambdaQueryWrapper<SysUser> wrapper  = new LambdaQueryWrapper<>();
        wrapper.in(SysUser::getRoleId, "[\""+id+"\"]");
        log.info("id------{}",id);
        List<SysUser> list = iSysUserService.list(wrapper);
        log.info("list----{}",list);
        if (list != null && list.size() != 0){
            return ResultData.error("该数据绑定有用户不能删除");
        }

        iSysRoleService.removeById(id);
        //删除对应菜单数据
        LambdaQueryWrapper<SysRoleMenu> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SysRoleMenu::getRoleId, id);
        iSysRoleMenuService.remove(lqw);

        ResultData resultData = new ResultData();
        resultData.setData("删除成功");
        resultData.setErrmsg("删除成功");
        resultData.setErrno(0);
        return resultData;
    }


    /**
     * 添加角色表
     *
     * @param sysRoleDto
     * @return
     */
    @PostMapping("add")
    public ResultData add(@RequestBody SysRoleDto sysRoleDto) {
        log.info("接收前端传输数据为:{}", sysRoleDto);
        // 添加基本数据到角色表
        sysRoleDto.setId(UUID.randomUUID().toString());
        sysRoleDto.setCreateDate(LocalDateTime.now());
        sysRoleDto.setDelFlag("0");
        sysRoleDto.setSuperadmin(0);
        sysRoleDto.setDefaultData("0");
        iSysRoleService.save(sysRoleDto);
        // 添加角色表和菜单表之间的对应关系
        String id = sysRoleDto.getId();
        // 获取 权限
        List<String> role_menus = sysRoleDto.getRole_menus();
        for (String role_menu : role_menus) {
            // 创建 角色-菜单对象
            SysRoleMenu sysRoleMenu = new SysRoleMenu();
            // 添加数据
            sysRoleMenu.setRoleId(id);
            sysRoleMenu.setMenuId(role_menu);
            iSysRoleMenuService.save(sysRoleMenu);
        }

        ResultData resultData = new ResultData();
        resultData.setData("添加成功");
        resultData.setErrmsg("添加成功");
        resultData.setErrno(0);
        return resultData;

    }

    /**
     * 查询全部角色列表
     *
     * @param sysRole
     * @return
     */
    @GetMapping("allData")
    public ResultData allDate(SysRole sysRole) {
        LambdaQueryWrapper<SysRole> lqw = new LambdaQueryWrapper();
        lqw.eq(SysRole::getDelFlag, 0);
        lqw.orderByDesc(SysRole::getCreateDate);
        List<SysRole> list = iSysRoleService.list(lqw);
        ResultData resultData = new ResultData();
        resultData.setErrno(0);
        resultData.setErrmsg("查询成功");
        resultData.setData(list);

        return resultData;
    }

    /**
     * 角色列表-分页
     *
     * @param page
     * @param limit
     * @param name
     * @return
     */
    @GetMapping("list")
    public ResultData list(Integer page, Integer limit, String name) {
        log.info("前端传输数据:{},{},{}", page, limit, name);
        // 分页构建器
        Page pageInfo = new Page(page, limit);
        // 条件构建器
        LambdaQueryWrapper<SysRole> lqw = new LambdaQueryWrapper();
        // 添加过滤条件,name不为空时,进行查询
        lqw.like(StringUtils.isNotEmpty(name), SysRole::getName, name);
        // 根据修改时间进行排序
        lqw.orderByDesc(SysRole::getUpdateDate);
        // 调用page方法
        iSysRoleService.page(pageInfo, lqw);


        // 获取当前页数据
        List<SysRole> records = pageInfo.getRecords();

        records = records.stream().map((record) -> {
            SysRoleDto sysRoleDto = new SysRoleDto();
            // 对拷
            BeanUtils.copyProperties(record, sysRoleDto);
            LambdaQueryWrapper<SysRoleMenu> wrapper = new LambdaQueryWrapper();
            // 给sysRoleDto的角色id赋值
            sysRoleDto.setRole_id(record.getId());

            // 设置查询条件:两个角色id相等
            wrapper.eq(SysRoleMenu::getRoleId, sysRoleDto.getId());
            // 调用查询
            List<SysRoleMenu> list = iSysRoleMenuService.list(wrapper);

            // 遍历查询到的数据 获得权限数组
            ArrayList<String> strings = new ArrayList<>();
            for (SysRoleMenu sysRoleMenu : list) {
                strings.add(sysRoleMenu.getMenuId());
            }
            sysRoleDto.setRole_menus(strings);

            return sysRoleDto;
        }).collect(Collectors.toList());
        // 排序


// 设置响应数据
        HashMap<String, Object> result = new HashMap<>();
        Integer total = Math.toIntExact(pageInfo.getTotal());
        result.put("count", total);//总数
        result.put("totalPages", Math.toIntExact(pageInfo.getPages()));//总页数
        result.put("pageSize",Math.toIntExact(pageInfo.getSize()) );//每页数量
        result.put("currentPage", Math.toIntExact(pageInfo.getCurrent()));//当前页码
        result.put("data",records);

        return ResultData.ok("",result);
    }


}
